//
//  CompanyListVC.swift
//  SBSafetyApp
//
//  Created by Lina on 2023/11/28.
//

import Foundation
import UIKit

class CompanyListVC: SubLevelViewController, PullToRefreshPresentable {
    let tableView = UITableView(frame: .zero, style: .plain)

    var datas: [CompanyModal?] = []

    var pageNum: Int = 1
    var totalPage: Int64 = 0
    var param: CompanyParam = CompanyParam(pageSize: 10)

    open var didSelectCompanysWith:((_ company: CompanyModal?) -> ())?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        view.backgroundColor = .white
        title = "维保单位列表"
        
        pageNum = 1
        setupUI()
        setupNavItems()
        setupPullToRefresh(on: tableView)
        reloadData()
    }
    
    deinit {
        tableView.removeAllPullToRefresh()
    }
    
    func reloadAction() {
        pageNum = 1
        reloadData()
    }
    
    func loadAction() {
        if pageNum >= totalPage {
            return
        }
        pageNum += 1
        reloadData()
    }
    
    func reloadData() {
        param.pageNum = pageNum
        API.getCompanys(withParam: param) { responseModel in
            DispatchQueue.main.async {
                if self.pageNum > 1 && (responseModel.models == nil || responseModel.models?.count == 0) {
                    self.pageNum -= 1
                    return
                }
                if self.pageNum == 1 {
                    self.datas.removeAll()
                }
                self.totalPage = responseModel.totalPage
                self.datas.append(contentsOf: responseModel.models ?? [])
                self.tableView.tableShowEmpty(withDataCount: self.datas.count)
                self.tableView.reloadData()
            }
        }
    }
    
    @objc func searchTapped() {
        let listV = CompanySearchVC()
        listV.didSelectCompanyWith = { (name) -> () in
            self.param.gcsmc = name
            self.pageNum = 1
            self.reloadData()
        }
        navigationController?.pushViewController(listV, animated: true)
    }
    
    // MARK: - Setup
    
    func setupUI() {
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = .white
        tableView.delegate = self
        tableView.dataSource = self
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
        }
    }
    
    func setupNavItems() {
        let searchBtn = UIButton(type: .custom)
        searchBtn.setImage(UIImage(named: "ic_search"), for: .normal)
        searchBtn.addTarget(self, action: #selector(searchTapped), for: .touchUpInside)
        searchBtn.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
        searchBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 0)
        let searchBar = UIBarButtonItem(customView: searchBtn)

        navigationItem.rightBarButtonItems = [searchBar]
    }
}

extension CompanyListVC: UITableViewDataSource, UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return datas.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let data = datas[indexPath.row]
        let ID : String = "CompanyListCell"
            
        var cell = tableView.dequeueReusableCell(withIdentifier: ID)
        if cell == nil {
            cell = CompanyListCell(style: .subtitle, reuseIdentifier: ID)
        }
        
        (cell as? CompanyListCell)?.reload(withModal: data)
        return cell!
    }
    
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return 54
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let m = datas[indexPath.row]
        didSelectCompanysWith?(m)
        navigationController?.popViewController(animated: true)
    }
}

